package com.hc.appanimal;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.hc.DTO.AnimalCategoryMasterDTO;
import com.hc.DTO.LoginDTO;
import com.hc.DTO.MessageDTO;
import com.hc.DTO.TokenDTO;
import com.hc.adapter.AnimalCategoryMasterAdapter;
import com.hc.common.ActionEvent;
import com.hc.constants.Constants;
import com.hc.controller.AnimalCategoryMasterController;
import com.hc.model.utils.MessageModel;
import com.hc.model.utils.TokenModel;
import com.hc.webservice.InternetUtils;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.OnEditorActionListener;
import android.widget.GridView;

public class HomeActivity extends Activity implements OnClickListener,
		OnItemClickListener {
	ArrayList<Object> arrData;
	AnimalCategoryMasterAdapter adapter;
	TextView txtTitle;
	EditText edSearchName;
	private GridView grid;
	int key_GMC;
	Bundle data;
	ImageView img_view_push_messages, img_new_push_message, contact_us, update;
	private Timer autoUpdate;
	public boolean flag = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		data = getIntent().getExtras();
		key_GMC = data.getInt("key_GMC");
		img_view_push_messages = (ImageView) findViewById(R.id.img_view_push_messages);
		img_new_push_message = (ImageView) findViewById(R.id.img_new_push_message);

		// this.runOnUiThread(new Runnable() {
		//
		// @Override
		// public void run() {
		// MessageModel modelMess = MessageModel.getInstance();
		// MessageDTO messDTO = modelMess.getMessage(HomeActivity.this);
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		// String currentDay = sdf.format(new Date());
		// if (messDTO.getDatemessage().equalsIgnoreCase(currentDay)) {
		// img_view_push_messages
		// .setImageResource(R.drawable.view_push_messages_new1);
		// }
		//
		// }
		// });
		contact_us = (ImageView) findViewById(R.id.contact_us);
		update = (ImageView) findViewById(R.id.update);
		img_view_push_messages.setOnClickListener(this);
		img_new_push_message.setOnClickListener(this);
		contact_us.setOnClickListener(this);
		update.setOnClickListener(this);
		txtTitle = (TextView) findViewById(R.id.txtTitle);
		txtTitle.setText("Species Identification Guide  Ver 1.0");
		txtTitle.setTextSize(15);
		grid = (GridView) findViewById(R.id.grid);
		initImageLoader(getApplicationContext());

		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int width = dm.widthPixels;
		int height = dm.heightPixels;
		int dens = dm.densityDpi;
		double wi = (double) width / (double) dens;
		double hi = (double) height / (double) dens;
		double x = Math.pow(wi, 2);
		double y = Math.pow(hi, 2);
		double screenInches = Math.sqrt(x + y);

		if (screenInches >= 4.0) {
			grid.setNumColumns(3);
		} else {
			grid.setNumColumns(2);
		}
		arrData = new ArrayList<Object>();
		InitData();
		adapter = new AnimalCategoryMasterAdapter(this, R.layout.grid_row,
				arrData);

		grid.setAdapter(adapter);
		grid.setOnItemClickListener(this);
		edSearchName = (EditText) findViewById(R.id.edSearchName);

		edSearchName.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (!newArr.contains(null)) {
					String text = edSearchName.getText().toString()
							.toLowerCase(Locale.getDefault());
					filter(text);
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		edSearchName.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
					performSearch();
					return true;
				}
				return false;
			}
		});

	}

	public class VerySlowTaskGMC extends AsyncTask<Void, Void, Void> {
		TokenModel model = TokenModel.getInstance();
		TokenDTO token = model.getToken(HomeActivity.this);
		String t = "";
		String _id;
		String dateupdate;
		LoginDTO logindto;

		public VerySlowTaskGMC(String id) {
			_id = id;
		}

		@Override
		protected Void doInBackground(Void... params) {
			String url = Constants.URL_REGISTER_PUSH
					+ _id + "&provider=ANDROID";
			HttpEntity httpEntity = null;
			HttpClient client = new DefaultHttpClient();
			HttpGet method = new HttpGet(url);
			method.setHeader("Content-Type",
					"application/x-www-form-urlencoded;charset=UTF-8");
			method.setHeader("Authorization", token.getToken_type() + " "
					+ token.getAccess_token());
			try {
				HttpResponse response = client.execute(method);
				httpEntity = response.getEntity();

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

		}

	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

		// Checks the orientation of the screen
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			grid.setNumColumns(3);

		} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
			DisplayMetrics dm = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(dm);
			int width = dm.widthPixels;
			int height = dm.heightPixels;
			int dens = dm.densityDpi;
			double wi = (double) width / (double) dens;
			double hi = (double) height / (double) dens;
			double x = Math.pow(wi, 2);
			double y = Math.pow(hi, 2);
			double screenInches = Math.sqrt(x + y);

			if (screenInches >= 4.0) {
				grid.setNumColumns(3);
			} else {
				grid.setNumColumns(2);
			}
		}
	}

	public void performSearch() {
		String search = edSearchName.getText().toString();
		if (!search.equalsIgnoreCase("")) {
			Intent intent = new Intent(HomeActivity.this, AnimalActivity.class);

			Bundle bundle = new Bundle();
			bundle.putString("keyseach", search);
			bundle.putInt("Search", 1);
			intent.putExtras(bundle);
			startActivity(intent);
		} else {

		}

	}

	public static void initImageLoader(Context context) {
		// This configuration tuning is custom. You can tune every option, you
		// may tune some of them,
		// or you can create default configuration by
		// ImageLoaderConfiguration.createDefault(this);
		// method.
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.diskCacheFileNameGenerator(new Md5FileNameGenerator())
				.diskCacheSize(50 * 1024 * 1024)
				// 50 Mb
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.writeDebugLogs() // Remove for release app
				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
	}

	public void filter(String charText) {
		charText = charText.toLowerCase(Locale.getDefault());
		arrData.clear();
		if (charText.length() == 0) {
			arrData.addAll(newArr);
			adapter.notifyDataSetChanged();
		} else {
			for (AnimalCategoryMasterDTO contacts : newArr) {
				if (contacts.getAnimalCategory()
						.toLowerCase(Locale.getDefault()).contains(charText)) {
					arrData.add(contacts);
					adapter.notifyDataSetChanged();
				}
			}
		}

	}

	public void InitData() {
		ActionEvent e = new ActionEvent(HomeActivity.this,
				Constants.GET_ALL_CATEGORY, null, null);
		AnimalCategoryMasterController.getInstance().handleViewEvent(e);
	}

	ArrayList<AnimalCategoryMasterDTO> newArr;

	@SuppressWarnings("unchecked")
	public void handleControllerViewEvent(ActionEvent e) {
		switch (e.action) {
		case Constants.GET_ALL_CATEGORY:
			newArr = (ArrayList<AnimalCategoryMasterDTO>) e.viewData;
			new VerySlowTask(newArr).execute();
			break;
		default:
			break;
		}
	}

	// sysAnimal
	public class VerySlowTask extends AsyncTask<String, Object, Void> {
		List<AnimalCategoryMasterDTO> _newArr;

		public VerySlowTask(List<AnimalCategoryMasterDTO> arr) {
			_newArr = arr;
		}

		@Override
		protected Void doInBackground(String... params) {
			try {
				for (int i = 0; i < _newArr.size(); i++) {
					publishProgress(_newArr.get(i));

				}
			} catch (Exception e) {
				// TODO: handle exception
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Object... values) {
			arrData.add(values[0]);

		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			adapter.notifyDataSetChanged();

			if (key_GMC == 1) {
				String idkey = data.getString("regId");
				new VerySlowTaskGMC(idkey).execute();
			}
		}

	}

	// @Override
	// public void onItemClick(AdapterView<?> parent, View view, int position,
	// long id) {
	// try {
	// AnimalCategoryMasterDTO dto = (AnimalCategoryMasterDTO) grid
	// .getItemAtPosition(position);
	// Intent intent = new Intent(HomeActivity.this, AnimalActivity.class);
	// Bundle data = new Bundle();
	// data.putSerializable("animal", dto);
	// data.putSerializable("token", tokenDTO);
	// intent.putExtras(data);
	// startActivity(intent);
	// } catch (Exception e) {
	// // TODO: handle exception
	// }
	// }

	@SuppressLint("SimpleDateFormat")
	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {

		case R.id.img_view_push_messages:
			if (InternetUtils.getInstance().isConnectingToInternet(
					HomeActivity.this)) {
				intent = new Intent(HomeActivity.this,
						ViewMessageActivity.class);

				startActivity(intent);
			} else {
				Toast.makeText(HomeActivity.this, "no net work",
						Toast.LENGTH_LONG).show();
			}

			break;

		case R.id.img_new_push_message:
			intent = new Intent(HomeActivity.this, UpdateAnimalActivity.class);

			startActivity(intent);
			break;
		case R.id.contact_us:
			intent = new Intent(HomeActivity.this, ContactUsActivity.class);
			startActivity(intent);
			break;
		case R.id.update:
			TokenModel tokenModel = TokenModel.getInstance();
			TokenDTO tokenDTO = tokenModel.getToken(HomeActivity.this);
			String dateExpires = tokenDTO.getExpires();
			Date date2 = null;
			Date date1 = null;
			String pattern = "EEE, dd MMM yyyy HH:mm:ss Z";
			SimpleDateFormat format = new SimpleDateFormat(pattern,
					Locale.ENGLISH);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String currentDay = sdf.format(new Date());
			String currentDayExpires = format.format(new Date());
			try {
				date1 = format.parse(currentDayExpires);
				date2 = format.parse(dateExpires);
				if (date1.compareTo(date2) < 0) {
					if (InternetUtils.getInstance()
							.isConnectingToInternet(this)) {
						this.runOnUiThread(new Runnable() {

							@Override
							public void run() {
								String path = Constants.URL_CATEGORY;
								String[] strs = path.split("/");
								File file = new File(Environment
										.getExternalStorageDirectory()
										+ "/"
										+ Constants.APP_NAME
										+ "/"
										+ strs[4]
										+ "/");
								// deleteDirectory(file);
								DeleteRecursive(file);
								adapter.notifyDataSetChanged();
								grid.invalidateViews();

							}
						});
						new AsystaskUpdateAnimal(currentDay, tokenDTO,
								HomeActivity.this).execute();
						flag = true;
						// arrData = new ArrayList<Object>();
						// InitData();
						// adapter = new AnimalCategoryMasterAdapter(this,
						// R.layout.grid_row,
						// arrData);
						adapter.notifyDataSetChanged();
					} else {
						Toast.makeText(HomeActivity.this, "no network",
								Toast.LENGTH_LONG).show();
					}
				}
			} catch (Exception e) {
				// TODO: handle exception
			}

			break;
		default:
			break;
		}

	}
	private void DeleteRecursive(File fileOrDirectory) {
	    if (fileOrDirectory.isDirectory())
	        for (File child : fileOrDirectory.listFiles())
	        {
	            child.delete();
	            DeleteRecursive(child);
	        }

	    fileOrDirectory.delete();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		autoUpdate = new Timer();
		autoUpdate.schedule(new TimerTask() {
			@Override
			public void run() {
				runOnUiThread(new Runnable() {
					public void run() {
						MessageModel modelMess = MessageModel.getInstance();
						MessageDTO messDTO = modelMess
								.getMessage(HomeActivity.this);
						SimpleDateFormat sdf = new SimpleDateFormat(
								"yyyy-MM-dd");
						String currentDay = sdf.format(new Date());
						if (messDTO.getDatemessage().equalsIgnoreCase(
								currentDay)) {
							img_view_push_messages
									.setImageResource(R.drawable.view_push_messages_new1);
						}
						if (flag) {
							// adapter.notifyDataSetChanged();

							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									ImageLoader.getInstance().clearDiskCache();
									ImageLoader.getInstance()
											.clearMemoryCache();
									flag = false;
									adapter.notifyDataSetChanged();
									grid.invalidateViews();
								}
							});
						}
					}
				});
			}
		}, 0, 5000);

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		AnimalCategoryMasterDTO dto = (AnimalCategoryMasterDTO) grid
				.getItemAtPosition(position);
		Intent intent = new Intent(HomeActivity.this, AnimalActivity.class);
		Bundle data = new Bundle();
		data.putSerializable("animal", dto);
		data.putInt("Search", 2);
		intent.putExtras(data);
		startActivity(intent);
	}

}
